<?
class Product
{
  public static function query_database($query)        //       
  {                                                    //  All this is
    $dbh = new PDO ('sqlite:/var/www/database.db');    //  duplicate code 
    $result = $dbh->query($query);                     //  in Users.class.php
    $rows= $result->fetchAll();                        //
    return $rows;                                      //
  }                                                    //  Dont do this in real life!
                                                       // 
  public static function exec_database($to_exec)       // 
  {                                                    // 
    $dbh = new PDO ('sqlite:/var/www/database.db');    // 
    $result = $dbh->exec($to_exec);                    //
    return $result;                                    // 
  }                                                    //      

  function set_from_database()
  {
    $me=self::query_database("SELECT id, name, description, price FROM products WHERE id = ".$this->id." ");
    $this->name        = $me[0]['name'];
    $this->description = $me[0]['description'];
    $this->price       = $me[0]['price'];
  }

  function set_from_web_post($the_request) // A HTTP Request
  {
    $this->name        = $the_request['name'];
    $this->description = $the_request['description'];
    $this->price       = $the_request['price'];
  }
  
  function to_html()
  {
    print "<ul>";
    print "<li>".$this->id          ."";
    print "<li>".$this->name        ."";
    print "<li>".$this->description ."";
    print "<li>".$this->price       ."";    
    print "</ul>";
  }

  function __construct($id)
  {
    $this->id = $id;
  }

  function save()
  {
    $query = "SELECT id, name, description, price FROM products WHERE id = ".$this->id." ";
    $rows = self::query_database($query);
    if ($rows)
      {
        // Table fields: id, name, description, price 
        $result = self::exec_database("UPDATE products SET name        ='".$this->name."', 
                                                           description ='".$this->description."', 
                                                           price       = '".$this->price."' 
                                       WHERE id = ".$this->id."");
      }
    else
      {
        $result = self::exec_database("INSERT INTO products VALUES (".$this->id.", '".$this->name."', '".$this->description."', ".$this->price.")");
      }
  }
}
?>
